<template>
  <div class="mobile-questionnaire-stats">
    <van-nav-bar 
      title="问卷统计" 
      left-text="返回"
      left-arrow
      @click-left="goBack"
    />
    <div class="content" v-if="stats">
      <h2 class="title">{{ questionnaireTitle }}</h2>
      <p class="desc">答卷总数：<b>{{ stats.totalSubmissions }}</b></p>
      <div v-for="q in stats.questions" :key="q.id" class="stat-block">
        <div class="question-title">{{ q.orderNum + 1 }}. {{ q.content }}</div>
        <div v-if="q.questionType !== 'text'">
          <div v-for="opt in q.options" :key="opt.optionValue" class="option-stat">
            <span>{{ opt.optionLabel }}</span>
            <van-progress :percentage="getPercent(opt.count, q.total)" pivot-text="{{ opt.count }}人" />
          </div>
        </div>
        <div v-else>
          <div class="text-answers">
            <div v-for="(ans, idx) in q.answers" :key="idx" class="text-answer">{{ ans }}</div>
          </div>
        </div>
      </div>
    </div>
    <van-empty v-else description="加载中..." />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'
import { getQuestionnaireStats, getQuestionnaireDetail } from '@/api/questionnaire'

const route = useRoute()
const router = useRouter()
const stats = ref(null)
const questionnaireTitle = ref('')

function goBack() {
  router.back()
}

function getPercent(count, total) {
  if (!total) return 0
  return Math.round((count / total) * 100)
}

async function loadStats() {
  const id = route.params.id
  try {
    const [statRes, detailRes] = await Promise.all([
      getQuestionnaireStats(id),
      getQuestionnaireDetail(id)
    ])
    stats.value = statRes.data
    questionnaireTitle.value = detailRes.data.title
  } catch (e) {
    showToast('加载失败')
  }
}

onMounted(loadStats)
</script>

<style scoped>
.mobile-questionnaire-stats {
  min-height: 100vh;
  background: #f7f8fa;
}
.content {
  padding: 16px;
}
.title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 8px;
}
.desc {
  color: #666;
  margin-bottom: 16px;
}
.stat-block {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}
.question-title {
  font-weight: 500;
  margin-bottom: 8px;
}
.option-stat {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  gap: 8px;
}
.text-answers {
  margin-top: 8px;
}
.text-answer {
  background: #f5f5f5;
  border-radius: 6px;
  padding: 6px 10px;
  margin-bottom: 6px;
  font-size: 13px;
  color: #333;
}
</style> 